package com.chopperdrop;

 

import java.io.InputStream;
import java.util.Iterator;
import java.util.Queue;
import java.util.Stack;
import java.util.Vector;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Picture;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.AnimationDrawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SubMenu;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.SurfaceHolder.Callback;
import android.widget.ImageView;

public class Playtime extends Activity implements Callback
{
	
	private Playtime self;
	//private Context context;
	public int chester =0;
	public int cheeta =0;
	public ball myBall;
	public paddle myPaddle;
	public chopper hisPaddle;
	public SurfaceView myview;
	public SurfaceHolder myholder;
	public PointF gridcenter;
	public Paint backgroundpaint;
	public Paint textpaint;	
	public Paint ballpaint;
	public Paint paddlepaint;	
	public AnimationDrawable particles;
	public ImageView imageAnim;
	public static boolean didCollide=false;
	public boolean isLocked=false;
	public int counter=0;
	Matrix matrix = new Matrix();
	public static char collidedAt;
	public static float xcol;
	public static float ycol;
	public Canvas c;
	
	public Bitmap bitmapTable, bitmapBall, bitmapRed, bitmapBlue;
	public InputStream isTable,isBall,isRed,isBlue;

	Stack<InputStream> isParticle = new Stack<InputStream>();
	Stack<Bitmap> bitmapParticle = new Stack<Bitmap>();


	private physics p;
	private MediaPlayer mp = null;
	private MediaPlayer FXPlayer;
	private int SFX = 1;
	
	private float hratio;
	private float wratio;   
	
	public int my_score = 0;
	public int his_score = 0;
	public int win_score = 1000;
	
	private float AI_response;
	
	private static final int EASY = 1;
	private static final int MEDIUM = 2;
	private static final int HARD = 3;
	private static final int EXPERT = 4;
	private static final int SOUND = 5;
	
	protected AlertDialog.Builder builder ;
	
	





	

	@Override
	public boolean onCreateOptionsMenu(Menu menu) 
	{
	  boolean result = super.onCreateOptionsMenu(menu);

	  SubMenu AI_Menu = menu.addSubMenu("Difficulty Level");
	  AI_Menu.add(0, EASY, 0, "Easy");
	  AI_Menu.add(0, MEDIUM, 0, "Medium");
	  AI_Menu.add(0, HARD, 0, "Hard");
	  AI_Menu.add(0, EXPERT, 0, "Expert");
	  
	  menu.add(0, SOUND, 0, "Sound On/Off");
	  
	  return result;
	}

	/* Handles menu item selections */
	public boolean onOptionsItemSelected(MenuItem item) 
	{

	    switch (item.getItemId())
	    {
	    case EASY:	
	    	AI_response = (float) .25;

	    	return true;

	    case MEDIUM:
	    	AI_response = (float) .45;

	    	return true;

	    case HARD:
	    	AI_response = (float) .75;

	    	return true;

	    case EXPERT:
	    	AI_response = (float) .85;
 
	    	return true;
	    	
	    case SOUND:

	    	SFX *=-1;
	    	return true;
	    }
	    p.resume();
	    return false;
	}


	

    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        self = this;
        setContentView(R.layout.play);
        myview = (SurfaceView) findViewById(R.id.surface);
        myholder = myview.getHolder();
        gridcenter = new PointF(50, 0);
        backgroundpaint = new Paint();
        textpaint = new Paint();
        ballpaint = new Paint();
        paddlepaint = new Paint();
        myBall = new ball(gridcenter.x, gridcenter.y);
        myPaddle = new paddle();
        hisPaddle = new chopper(10);
        myBall = new ball(hisPaddle.xpos, hisPaddle.ypos);
        backgroundpaint.setColor(Color.BLACK);
        textpaint.setColor(Color.GRAY);
        ballpaint.setColor(Color.GREEN);
        paddlepaint.setColor(Color.RED);
		isTable=this.getResources().openRawResource(R.drawable.table);
		bitmapTable = BitmapFactory.decodeStream(isTable);
		isBall=this.getResources().openRawResource(R.drawable.ball);
		bitmapBall = BitmapFactory.decodeStream(isBall);
		isBlue=this.getResources().openRawResource(R.drawable.chopper);
		bitmapBlue = BitmapFactory.decodeStream(isBlue);
		isRed=this.getResources().openRawResource(R.drawable.redpaddle);
		bitmapRed = BitmapFactory.decodeStream(isRed);
		
		isParticle.push(this.getResources().openRawResource(R.drawable.sparks1));
		isParticle.push(this.getResources().openRawResource(R.drawable.sparks2));
		isParticle.push(this.getResources().openRawResource(R.drawable.sparks3));
		isParticle.push(this.getResources().openRawResource(R.drawable.sparks4));
		isParticle.push(this.getResources().openRawResource(R.drawable.sparks5));
		isParticle.push(this.getResources().openRawResource(R.drawable.sparks6));
		isParticle.push(this.getResources().openRawResource(R.drawable.sparks7));
		isParticle.push(this.getResources().openRawResource(R.drawable.sparks8));
		isParticle.push(this.getResources().openRawResource(R.drawable.sparks9));
		isParticle.push(this.getResources().openRawResource(R.drawable.sparks10));
		isParticle.push(this.getResources().openRawResource(R.drawable.sparks11));
		isParticle.push(this.getResources().openRawResource(R.drawable.sparks12));
		isParticle.push(this.getResources().openRawResource(R.drawable.sparks13));
		isParticle.push(this.getResources().openRawResource(R.drawable.sparks14));
		isParticle.push(this.getResources().openRawResource(R.drawable.sparks15));
		isParticle.push(this.getResources().openRawResource(R.drawable.sparks16));
		
		for(int i=0;i<16;i++)
		{
			bitmapParticle.push(BitmapFactory.decodeStream(isParticle.get(i)));
		}

        
        AI_response = (float) .45;
        myholder.addCallback(self);
        FXPlayer = new MediaPlayer();
        
        builder = new AlertDialog.Builder(this);        
		builder.setCancelable(false)
	       .setPositiveButton("Yes", new DialogInterface.OnClickListener() 
	       {
	           public void onClick(DialogInterface dialog, int id) 
	           {
	        	   my_score =0;
	        	   his_score =0;
	        	   dialog.cancel();
	           }
	       })
	       .setNegativeButton("No", new DialogInterface.OnClickListener() 
	       {    		    	   
	           public void onClick(DialogInterface dialog, int id) 
	           {
	        	   self.finish();    		                
	           }
	       });
    }
    
    @Override
    public boolean onTouchEvent(MotionEvent event) 
    {    		
        if (event.getAction() == MotionEvent.ACTION_DOWN) 
        {
            float p = event.getX();
            p = p / wratio;
            myPaddle.xpos = p;
            myPaddle.padpos.add(myPaddle.xpos);
            myPaddle.xvel = 0;
        } 
        else if (event.getAction() == MotionEvent.ACTION_MOVE)
        {
            float p = event.getX();
            p = p / wratio;
            myPaddle.xpos = p;
            
            long current_time = System.currentTimeMillis();
            long dt = current_time - myPaddle.last_update;
            myPaddle.last_update = current_time;
            myPaddle.xvel = (myPaddle.xpos - myPaddle.padpos.get(1)) *dt;
            myPaddle.padpos.add(myPaddle.xpos);
            
        }
        else if (event.getAction() == MotionEvent.ACTION_UP)
        {
            float p = event.getX();
            p = p / wratio;
            myPaddle.xpos = p;
            myPaddle.padpos.add(myPaddle.xpos);
            myPaddle.xvel = 0;        	
        }	
        if (!p.playing)
    	{
        	//handle_win();
    	}
        
        return false;
    }

    @Override
	public void surfaceCreated(SurfaceHolder holder)
	{
		p = new physics();
		mp = MediaPlayer.create(this, R.raw.benny);
        mp.setLooping(true);
        //mp.start();
		p.start();
	}
	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height){
	}
	@Override
	public void surfaceDestroyed(SurfaceHolder holder)
	{
		if (mp != null) 
		{
			mp.stop();
			mp.release();
			mp = null;
		}
		try {
			p.safeStop();
		} finally {
			p = null;
		}		
	}
    
    public class physics extends Thread
    {
    	private volatile boolean running = true;
    	private volatile boolean playing = false;
    	@Override
    	public void run() 
    	{
            while (running) 
            {
            	drawit();
            	update_hisPad();
            	update_ball();
            	/*if ((myBall != null)&& playing) 
            	{
            		//collision();
            		
            		int x = myBall.update();
            		if (x == 1)
            		{
            			my_score++;
            			myBall.setPosition(hisPaddle.xpos, hisPaddle.ypos);
            			myBall.xacel =0;
            			playing = false;
            			//if (!FXPlayer.isPlaying())
            			//{
            			if (SFX == 1)
            			{
            			FXPlayer.release();
            			FXPlayer = MediaPlayer.create(self, R.raw.win_point);
            			FXPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            			FXPlayer.start();
            			}
            			//}		
            		}
            		if (x==-1)
            		{
            			his_score++;
            			myBall.setPosition(hisPaddle.xpos, hisPaddle.ypos);
            			myBall.xacel =0;
            			playing = false;

            			if (SFX == 1)
            			{
            			FXPlayer.release();
            			FXPlayer = MediaPlayer.create(self, R.raw.lose_point);
            			FXPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            			FXPlayer.start();
            			}
            		}
            		if (x==0 && SFX==1)
            		{ 

            			FXPlayer.release();
            			FXPlayer = MediaPlayer.create(self, R.raw.wall_bounce);
            			FXPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            			FXPlayer.start();
            		}     		
            	}*/
            }
    	}
        public void safeStop() 
        {
        	playing = false;
            running = false;
            interrupt();
        }
    }
     
    
    private void handle_win()
    {

    	if ((my_score >= win_score)||(his_score >= win_score))
    	{
    		p.safeStop();
    		finish();
    	}

    	else
    	{
        	//myBall.setPosition(hisPaddle.xpos, hisPaddle.ypos);
    		//myBall.setVelocity(0, -7);
    		//myBall.last_update = System.currentTimeMillis();
    		p.playing = true;
    	}
    }
    
  /*  public void collision()
    {
    	float yfault; //y boundary fault
    	float xfault; //x boundary fault
    	
    	//handle collision with myPaddle
    	yfault = (myBall.ypos + myBall.rad)
    	-(myPaddle.ypos -(myPaddle.height / 2));
    	if (myBall.xpos > myPaddle.xpos)
    		xfault = (myPaddle.xpos+(myPaddle.width/2))
    		-(myBall.xpos -myBall.rad);
    	else
    		xfault = (myBall.xpos +myBall.rad)
    		-(myPaddle.xpos-(myPaddle.width/2));
    	
    	if (yfault > 0)
    	{
    		if (xfault > 0)
    		{
    			if ((xfault>yfault)&&(myBall.ypos < myPaddle.ypos))
    			{
    				myBall.yvel = -1 * Math.abs(myBall.yvel); 
    				myBall.yacel = -1 * Math.abs(myBall.yacel);
    				
    				
    				
        			if(!didCollide)
        			{
        				didCollide=true;
        				collidedAt='b';
        				xcol=myBall.xpos;
        				ycol=myBall.ypos;
        			}
    			}				
    			else
    				myBall.xvel = -1 * Math.abs(myBall.yvel);
    			myBall.xacel = -1*myPaddle.xvel;

    			if (SFX == 1)
    			{
    				FXPlayer.release();
    				FXPlayer = MediaPlayer.create(self, R.raw.pad_bounce);
    				FXPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    				FXPlayer.start();
    			}

    		}
    	}
    	//handle collision with hisPaddle
    	yfault = (hisPaddle.ypos +(hisPaddle.height / 2))
    	-(myBall.ypos - myBall.rad);   	
    	if (myBall.xpos > hisPaddle.xpos)
    		xfault = (hisPaddle.xpos+(hisPaddle.width/2))
    		-(myBall.xpos -myBall.rad);
    	else
    		xfault = (myBall.xpos +myBall.rad)
    		-(hisPaddle.xpos-(hisPaddle.width/2));
    	
    	if (yfault > 0)
    	{
    		if (xfault > 0)
    		{
    			if ((xfault>yfault)&&(myBall.ypos > hisPaddle.ypos))
    			{
    				myBall.yvel = Math.abs(myBall.yvel);
    				myBall.yacel = Math.abs(myBall.yacel);
        			if(!didCollide)
        			{
        				didCollide=true;
        				collidedAt='t';
        				xcol=myBall.xpos;
        				ycol=myBall.ypos;
        			}
    			}
    			else
    				myBall.xvel = -1 * Math.abs(myBall.yvel);
    			myBall.xacel = -2*hisPaddle.xvel;

    			if (SFX == 1)
    			{
    				FXPlayer.release();
    				FXPlayer = MediaPlayer.create(self, R.raw.pad_bounce);
    				FXPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    				FXPlayer.start();
    			}

    		}
    	}
    }*/
//set and done to rotate the top of the screen
    public void update_hisPad()
    {
    	long current_time = System.currentTimeMillis();
    	long time_diff = current_time - hisPaddle.last_update;   
    	float newxpos = hisPaddle.xpos;
    	float newxvel = hisPaddle.xvel;
    	newxvel = 2;
    	hisPaddle.xvel = newxvel;
    	float BPdiff =  myBall.xpos - newxpos;
    	
    	if(hisPaddle.xpos <100 && chester ==0)
    	{
    		
    		
    		
    	
    		//newxpos += (newxvel * time_diff)/100;
    		newxpos += newxvel;
    		hisPaddle.xpos = newxpos;
    		hisPaddle.last_update = current_time;
    		
    	}
    	else if (hisPaddle.xpos==100)
    	{
    		hisPaddle.xvel = newxvel;
    		
    		newxpos -=2;
    		hisPaddle.xpos = newxpos;
    		hisPaddle.last_update = current_time;
    		chester =1;
    		
    	}
    	else if (hisPaddle.xpos==0)
    	{
    		hisPaddle.xvel = newxvel;
    		hisPaddle.last_update = current_time;
    		newxpos +=2;
    		hisPaddle.xpos = newxpos;
    		
    		chester = 0;
    	}
    	else if (hisPaddle.xpos <100 && chester ==1)
    	{
    		hisPaddle.xvel = newxvel;
    		hisPaddle.last_update = current_time;
    		newxpos -=2;
    		hisPaddle.xpos = newxpos;
    		
    	}
    	
    	/*
    	
    	if ((myBall.ypos < gridcenter.y*1.2)&&(myBall.yvel < 0))
    	{
    		float BPdiff =  myBall.xpos - newxpos;
    		newxvel = BPdiff * AI_response;
    	}
    	else
    		newxvel =0;
    	
    	
    	newxpos += (newxvel * time_diff)/100;


		hisPaddle.xpos = newxpos;
		hisPaddle.xvel = newxvel;
		hisPaddle.last_update = current_time; */
    }

    public void update_ball()
    {
    	long current_time = System.currentTimeMillis();
    	long time_diff = current_time - myBall.last_update;   
    	float newypos = myBall.ypos;
    	float newyvel = myBall.yvel;
    	newyvel = 2;
    	myBall.yvel = newyvel;
    	float BPdiff =  myBall.ypos - newypos;
    	
    	if(myBall.ypos <150)
    	{
    		
    		
    		
    	
    		
    		newypos += newyvel;
    		myBall.ypos = newypos;
    		myBall.last_update = current_time;
    		
    	}
    	else if (myBall.ypos==150)
    	{
    		myBall.setPosition(hisPaddle.xpos, hisPaddle.ypos);
    		
    	}
    	
    	
    	
    }

    
    void drawit()
    { 
    	c = null;
    	try {
    		c = myholder.lockCanvas();
    		if (c != null) 
    		{
    			hratio = c.getHeight()/myBall.ymax;
    			wratio = c.getWidth()/myBall.xmax;    			
    			//draw background
    			c.drawRect(0,0, c.getWidth(),c.getHeight(), backgroundpaint);

    	c.drawBitmap(bitmapTable, null,new Rect(0,0,c.getWidth(),c.getHeight()),null);
    			    			
    			/*//draw particle effect
    			if(didCollide)
    			{ 
    				switch(collidedAt)
    				{  
    				case 'b': 
    					c.save();
    					c.rotate(0);
        				c.drawBitmap(bitmapParticle.get(counter), xcol*wratio-myBall.rad*wratio-30, ycol*hratio-myBall.rad*wratio-50, null);
        				c.restore();
    					break;
    				case 't':
    					c.save();
    					c.rotate(180f,xcol*wratio-myBall.rad*wratio+10, ycol*hratio-myBall.rad*wratio+10);
        				c.drawBitmap(bitmapParticle.get(counter), xcol*wratio-myBall.rad*wratio-30, ycol*hratio-myBall.rad*wratio-50, null);
        				c.restore(); 
    					break;
    				case 'l':
    					c.save();
    					c.rotate(90f,xcol*wratio-myBall.rad*wratio+10, ycol*hratio-myBall.rad*wratio+10);
        				c.drawBitmap(bitmapParticle.get(counter), xcol*wratio-myBall.rad*wratio-50, ycol*hratio-myBall.rad*wratio-40, null);
        				c.restore();
    					break;
    				case 'r':
    					c.save();
    					c.rotate(270f,xcol*wratio-myBall.rad*wratio+10, ycol*hratio-myBall.rad*wratio+10);
        				c.drawBitmap(bitmapParticle.get(counter), xcol*wratio-myBall.rad*wratio-50, ycol*hratio-myBall.rad*wratio-40, null);
        				c.restore();
    					break;
    				}
    				counter++;
    				if(counter>15)
    				{
    					counter=0;
    					didCollide=false;
    				}
    			} */ 
    			
    			//draw ball 
    			c.drawBitmap(bitmapBall,null,new RectF((myBall.xpos-(myBall.width/2))*wratio,
    					(myBall.ypos-(myBall.height/2))*hratio,
    					(myBall.xpos+(myBall.width/2))*wratio,
    			 	(myBall.ypos+(myBall.height/2))*hratio), null);
    			//draw my paddle
    			c.drawBitmap(bitmapRed,null,new RectF((myPaddle.xpos-(myPaddle.width/2))*wratio,
    					(myPaddle.ypos-(myPaddle.height/2))*hratio,
    					(myPaddle.xpos+(myPaddle.width/2))*wratio,
    			 	(myPaddle.ypos+(myPaddle.height/2))*hratio), null);
    			
    			//draw opponent paddle
    			c.drawBitmap(bitmapBlue,null,new RectF((hisPaddle.xpos-(hisPaddle.width/2))*wratio,
    					(hisPaddle.ypos-(hisPaddle.height/2))*hratio,
    					(hisPaddle.xpos+(hisPaddle.width/2))*wratio,
    					(hisPaddle.ypos+(hisPaddle.height/2))*hratio), null);

    
    				

    		}
    	} finally {
    		if (c != null) 
    		{
    			myholder.unlockCanvasAndPost(c);
    		}
    	}
    }
}